<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>小球上下左右移动</title>
</head>
<body onkeydown="test()">

<canvas id="test" width="400px" height="300px;" style="background-color:black"></canvas>

<script >
    //得到画布
    var canvas1 = document.getElementById("test");
    //得到绘图上下文（可以理解是画笔）
    var cxt = canvas1.getContext("2d");

    var ballX = 30;
    var ballY = 30;

    drawBall();
    function drawBall() {
        //画出红色的圆球
        cxt.beginPath();
        cxt.fillStyle = '#ff0000';
        cxt.arc(ballX,ballY,10,0,2*Math.PI,true);
        cxt.fill();
    }


    //现在我按w d s a 可以移动小球
    function test() {
       //当按下键后事件--》event对象--》事件处理涵数
        var code = event.keyCode; //对应字母的ascii码

        switch (code){
            case 87:
               ballY--;
                break;
            case 68:
               ballX++;
                break;
            case 83:
                ballY++;
                break;
            case 65:
                ballX--;
                break;
        }
        //把画布清理
        cxt.clearRect(0,0,400,300);

        //重新绘制
        drawBall();

    }

</script>

</body>
</html>